<template>
  <div class="view-fill">
    <div class="app-container-flex">
      <NewFullScreen v-model="showDialog" :title="title">
        <template v-slot:full-button>
          <el-button :disabled="!canSave" @click="save()">保存</el-button>
        </template>
        <div class="model-panel" v-if="action !== 'add'">
          <div class="model-panel-title">
            <p>{{ $t('basic_information') }}</p>
          </div>
          <div class="model-panel-body">
            <BasicInformation
              :info="infoList"
              :labelWidth="infoList.labelWidth"
            >
            </BasicInformation>
          </div>
        </div>

        <div class="model-panel">
          <div class="model-panel-title">
            <Tooltip :text="$t('detailInfo')" />
          </div>
          <div class="model-panel-body">
            <!-- 条件栏 -->
            <page-filter :filter-list="filterInfo.list" v-if="action === 'add'">
              <template v-slot:filter-addProduct>
                <el-button @click="addProduct"> 添加产品 </el-button>
              </template>
              <template v-slot:filter-removeProduct>
                <el-button
                  :disabled="!canRemoveProduct"
                  @click="removeProduct()"
                  >删除产品</el-button
                >
              </template>
              <template v-slot:filter-productCodeScan>
                <ScanInputBox
                  :query="scanInfo.query"
                  :api="scanInfo.api"
                  @callback="onCallBackScanData"
                />
              </template>
            </page-filter>
            <p style="color: #ec808d">
              (注：请先扫描个体信息码，再扫描其绑定的RFID码)
            </p>
            <div class="flex_full_item">
              <el-form
                ref="tableForm"
                :model="tableInfo"
                style="width: 100%"
                @submit.native.prevent
              >
                <!-- 表格 -->
                <page-table
                  :refresh="tableInfo.refresh"
                  :init-curpage="tableInfo.initCurpage"
                  v-model:data="tableInfo.data"
                  :pager="false"
                  :summary="true"
                  :summary-field-list="tableInfo.summaryFieldList"
                  :tab-index="true"
                  :field-list="tableInfo.fieldList"
                  :handle="tableInfo.handle"
                  :row-class-name="tableRowClassName"
                  :isDynamic="true"
                  @handleEvent="handleEvent"
                >
                  <template v-slot:col-rfidCode="scope">
                    <el-form-item class="margin-bottom">
                      <div class="page-table-input-number-wrapper">
                        <div class="page-table-input-number-left">
                          <div class="page-table-input-number-item">
                            <el-form-item
                              :prop="`data.${scope.$index}.rfidCode`"
                              :rules="
                                scope.$index >= 0
                                  ? [
                                      {
                                        required: scope.$index >= 0,
                                        message: '请输入RFID码',
                                        trigger: 'blur',
                                      },
                                    ]
                                  : []
                              "
                            >
                              <el-input
                                v-model.lazy="scope.row.rfidCode"
                                style="width: 100%; margintop: 18px"
                                clearable
                                :min="0"
                                class="fridinput"
                                @keyup.enter="
                                  FRIDSearchInput(scope.row, scope.$index)
                                "
                                @focus="FRIDFocus(scope.row, scope.$index)"
                              />
                            </el-form-item>
                          </div>
                        </div>
                      </div>
                    </el-form-item>
                  </template>
                </page-table>
              </el-form>
            </div>
          </div>
        </div>
      </NewFullScreen>
    </div>
    <selectProduct
      v-if="selectDepotStorageInfo.visible"
      v-model:show-dialog="selectDepotStorageInfo.visible"
      :query="selectDepotStorageInfo.query"
      :api="getDepotStockCustomizeListPage"
      :tableKey="selectDepotStorageInfo.rightTableKey"
      :show-price="$permission('scrapExportOrder:price')"
      @callback="selectDepotStorageCallBack"
    />
  </div>
</template>

<script setup name="scrapExportOrderModify">
import ScanInputBox from './ScanInputBox'
import selectProduct from './selectProduct'
import { getDepotStockCustomizeListPage } from '@/api/stock'
import {
  createRfidBindList,
  searchNoBindDeliverOrderDetailList,
  searchNoBindReceivingOrderDetailList,
  scansWithSmart,
} from '@/api/smartCabinet'
import { getCustomizeSetting } from '@/api/customize'

const { proxy } = getCurrentInstance()
const emit = defineEmits()
const props = defineProps({
  visible: {
    type: Boolean,
  },
  title: {
    type: String,
  },
  action: {
    type: String,
  },
  exportId: {
    type: [Number, String],
  },
  baseData: {
    type: Object,
    default: function () {
      return {}
    },
  },
})
const formRefs = ref('')
const scanInfo = reactive({
  api: scansWithSmart,
  query: {},
})
const infoList = ref({
  data: { ...props.baseData },
  fieldList: [],
  labelWidth: '135px',
})
//表单相关
const formInfo = reactive({
  ref: null,
  data: {
    depotName: '',
    depotId: '',
    deptName: '',
    deptId: '',
    phone: '',
  },
  fieldList: [
    {
      label: '出库单号',
      value: 'orderNo',
      type: 'input',
      disabled: true,
    },
    {
      label: '出库仓库',
      value: 'depotName',
      type: 'slot',
      require: true,
    },
    {
      label: '出库部门',
      value: 'deptName',
      type: 'input',
      disabled: true,
    },
    {
      label: '是否寄售业务',
      value: 'isConsignBusinessValue',
      type: 'input',
      disabled: true,
      show:
        props.exportId &&
        proxy.$store.state.permission.systemConfig.is_consign_business == 1,
    },
    {
      label: '业务日期',
      value: 'businessDate',
      type: 'date',
      clearable: false,
    },
    {
      label: '备注',
      value: 'remark',
      type: 'textarea',
      maxlength: 200,
    },
  ],
  rules: {
    depotName: [
      { required: true, message: '请选择出库仓库', trigger: 'change' },
    ],
    businessDate: [
      { required: true, message: '请选择业务日期', target: 'blur' },
    ],
    phone: [{ validator: proxy.$validate.cellphone, trigger: 'blur' }],
  },
  labelWidth: '120px',
})
// 过滤相关配置
const filterInfo = reactive({
  query: {
    customizeUserVO: {},
    queryMap: {
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
    },
    queryParams: {},
  },
  list: [
    { type: 'slot', value: 'addProduct' },
    { type: 'slot', value: 'removeProduct' },
    { type: 'slot', value: 'productCodeScan' },
  ],
})
// 表格相关
const tableInfo = reactive({
  refresh: 1,
  initCurpage: 1,
  data: [],
  map: new Map(),
  isSysGroup: true, //新增修改页是否有后端合并
  sysGroup: [], //新增修改页后端合并项
  selections: [],
  summaryFieldList: [{ value: 'qty', formatter: proxy.$fn.qtyFormatter }],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '120',
    btList: [
      {
        label: '删除',
        event: removeProduct,
        popconfirmText: '删除后将改变数据,是否继续？',
        show: true,
      },
    ],
  },
})
const selectDepotStorageInfo = reactive({
  //库存产品
  visible: false,
  query: {
    depotId: {
      queryType: 'EQUALS',
      queryCategory: 'AND',
      value: null,
    },
    id: {
      queryType: 'NOT_IN',
      value: null,
    },
    generalProductCategory: {
      queryType: 'EQUALS',
      queryCategory: 'AND',
      value: 0,
    },
    isConsignBusiness: {
      queryType: 'EQUALS',
      queryCategory: 'AND',
      value: '',
    },
    isRfidManage: {
      queryType: 'EQUALS',
      queryCategory: 'AND',
      value: '1',
    },
    depotAuth: {
      asTbName: 'depot_stock',
      columnName: 'depot_id',
      queryType: 'IN',
      queryCategory: 'AND',
      value: 'depotAuth',
    },
  },
  rightTableKey:
    'smartCabinetRfidBindAddPageAddRight-com.slip.spd.entity.vo.stock.DepotStockVO',
})
const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emit('update:visible', newValue) // 更新父组件visible
  },
})

const canSave = computed(() => {
  return tableInfo.data.length
})
const canRemoveProduct = computed(() => {
  return tableInfo.selections.length
})

watch(
  () => props.action,
  (val) => {
    if (val && val !== 'add') {
      // 发货单绑定
      if (val === 'addBydeliverOrder') {
        infoList.value.fieldList = [
          {
            label: '发货单号',
            value: 'orderNo',
            type: 'text',
          },
          {
            label: '采购单号',
            value: 'purchNo',
            type: 'text',
          },

          {
            label: '供应商',
            value: 'supplierName',
            type: 'text',
          },
        ]
        searchNoBindDeliverOrderDetailList(props.baseData.id).then((resp) => {
          if (resp && resp.success) {
            tableInfo.data = resp.data
            // 导入绑定数据自动获取第一条数据焦点
            setFirstInputFocus()
          }
        })
      }
      // 入库单绑定
      if (val === 'addStorageOrder') {
        infoList.value.fieldList = [
          {
            label: '入库单号',
            value: 'orderNo',
            type: 'text',
          },
          {
            label: '入库仓库',
            value: 'depotName',
            type: 'text',
          },

          {
            label: '入库人',
            value: 'storeUserName',
            type: 'text',
          },
        ]
        searchNoBindReceivingOrderDetailList(props.baseData.id).then((resp) => {
          if (resp && resp.success) {
            tableInfo.data = resp.data
            // 导入绑定数据自动获取第一条数据焦点
            setFirstInputFocus()
          }
        })
      }
    }
  },
  {
    immediate: true,
  }
)

watch(
  () => tableInfo.data,
  (val) => {
    if (val.length && !tableInfo.isSysGroup) {
      tableInfo.data.forEach((row) => {
        let smallUnitQty = parseFloat(row.smallUnitQty || 0)
        let unitConvertCoefficient = parseFloat(row.unitConvertCoefficient || 1)
        let largeUnitQty = parseFloat(row.largeUnitQty || 0)
        let calcQty = proxy.$fn.accAdd(
          proxy.$fn.accMul(largeUnitQty, unitConvertCoefficient),
          smallUnitQty
        )
        let qty = proxy.$fn.accDiv(calcQty, unitConvertCoefficient)
        row['calcQty'] = calcQty
        row['qty'] = qty
        row.sumAmount = proxy.$fn.accDiv(
          proxy.$fn.accMul(calcQty, parseFloat(row.price)),
          unitConvertCoefficient
        )
        if (row.details && row.details.length) {
          row.details[0].qty = qty
          row.details[0].calcQty = calcQty
          row.details[0].largeUnitQty = largeUnitQty
          row.details[0].smallUnitQty = smallUnitQty
          row.details[0].sumAmount = row.sumAmount
        }
      })
    }
  },
  {
    deep: true,
  }
)

let obj = {
  rfidCode: {
    label: 'rfid码',
    value: 'rfidCode',
    type: 'slot',
  },
  qty: {
    label: '数量',
    value: 'qty',
    //type: 'slot',
    minWidth: '250px',
  },
  price: {
    label: '单价',
    value: 'price',
    minWidth: '150px',
    type: 'column',
    formatter: proxy.$fn.TripartiteMethod,
    permission: !proxy.$permission('scrapExportOrder:price'),
    hidden: true,
  },
  sumAmount: {
    label: '总金额',
    value: 'sumAmount',
    type: 'column',
    formatter: proxy.$fn.TripartiteMethod,
    permission: !proxy.$permission('scrapExportOrder:price'),
    hidden: true,
  },
  defaultSupplierPrice: {
    label: '默认供应商价格',
    value: 'defaultSupplierPrice',
    type: 'column',
    permission: !proxy.$permission('scrapExportOrder:price'),
    formatter: proxy.$fn.TripartiteMethod,
    hidden: true,
  },
  stockAvailableCalcQty: {
    label: '库存可用计算数量',
    value: 'stockAvailableCalcQty',
    type: 'column',
    minWidth: '150px',
  },
  scrapReason: {
    label: '报废原因',
    value: 'scrapReason',
    minWidth: '150px',
    type: 'slot',
    hidden: true,
  },
}
tableInfo.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...obj,
})
getCustomize()

onMounted(() => {
  formRefs.value = [proxy.$refs['tableForm'], formInfo.ref]
  proxy.$nextTick(() => {
    if (!props.exportId) {
      formInfo.fieldList = formInfo.fieldList.filter(
        (item) => item.value !== 'orderNo'
      )
    }
  })
})
let FRIDFocusRow = ref({})
function FRIDFocus(row, index) {
  FRIDFocusRow.value = row
}
function FRIDSearchInput(row, index) {
  getNextFridInput(row, index)
}
// 获取下一个扫RFID码焦点
function getNextFridInput(row, index) {
  proxy.$nextTick(() => {
    let tableInfoLength = tableInfo.data.length
    let _index = index
    let valueNum = 0
    if (tableInfoLength > _index + 1) {
      _index++
    }
    let fridInputs = document.getElementsByClassName('fridinput')
    let fridInputDom = fridInputs[_index]?.querySelector('.el-input__inner')
    let currentFridInputDom =
      fridInputs[index]?.querySelector('.el-input__inner')
    if (!fridInputDom || !currentFridInputDom.value) {
      return
    }
    // 校验是否是正确RFID码
    let params = {
      code: currentFridInputDom.value,
    }
    handleNext(
      fridInputs,
      valueNum,
      fridInputDom,
      _index,
      tableInfoLength,
      FRIDFocusRow,
      row
    )
    // scansNoNeedDepot(params)
    //   .then((res) => {
    //     if (res && res.success) {
    //       if (res.data.flag == 6) {
    //         handleNext(
    //           fridInputs,
    //           valueNum,
    //           fridInputDom,
    //           _index,
    //           tableInfoLength,
    //           FRIDFocusRow,
    //           row
    //         )
    //       } else {
    //         currentFridInputDom.value = ''
    //         proxy.$message({
    //           message: '请输入正确的RFID码',
    //           type: 'warning',
    //           duration: 3500,
    //           showClose: true,
    //         })
    //         return
    //       }
    //     } else {
    //       //currentFridInputDom.value = ''
    //       params.code = ''
    //       handleNext(
    //         fridInputs,
    //         valueNum,
    //         fridInputDom,
    //         _index,
    //         tableInfoLength,
    //         FRIDFocusRow,
    //         row
    //       )
    //     }
    //   })
    //   .catch((err) => {
    //     params.code = ''
    //   })
  })
}
function handleNext(
  fridInputs,
  valueNum,
  fridInputDom,
  _index,
  tableInfoLength,
  FRIDFocusRow,
  row
) {
  fridInputs.forEach((element) => {
    if (element.querySelector('.el-input__inner').value) {
      ++valueNum
    }
  })
  if (!fridInputDom.value) {
    fridInputDom.focus()
  } else {
    // 扫RFID码到最后一个自动获取扫产品焦点 或者 所有rfid码扫码完成自动获取扫码产品
    if (_index + 1 === tableInfoLength || valueNum === tableInfoLength) {
      document.getElementById('rfidInput').focus()
      FRIDFocusRow.value = {}
      tableRowClassName(row)
      return
    }
    // 获取下一个扫RFID码焦点
    getNextFridInput(row, _index)
  }
}
function setFirstInputFocus() {
  let tableInfoLength = tableInfo.data.length
  if (!tableInfoLength) {
    return
  }
  setInputFocus(0)
}
function setLastInputFocus() {
  let tableInfoLength = tableInfo.data.length
  if (!tableInfoLength) {
    return
  }
  setInputFocus(tableInfoLength - 1)
}
function setInputFocus(index) {
  setTimeout(() => {
    let fridInputs = document.getElementsByClassName('fridinput')
    let fridInputDom = fridInputs[index].querySelector('.el-input__inner')
    fridInputDom.focus()
  }, 200)
}
function tableRowClassName({ row = undefined }) {
  if (row?.id === FRIDFocusRow.value?.id) {
    return 'success-row'
  } else {
    return ''
  }
}

async function onCallBackScanData(data, callback) {
  //扫码回调
  if (tableInfo.data && tableInfo.data.length) {
    let currentIndex = 0
    let items = tableInfo.data.filter((row, index) => {
      if (row.id === data.id) {
        currentIndex = index
        return row
      }
    })
    if (items.length) {
      setInputFocus(currentIndex)
      //callback(true)
      return
    } else {
      callback(false)
    }
  }
  tableInfo.data = tableInfo.data.concat([data])
  setLastInputFocus()
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.selections = [...data]
      break
  }
}
function save() {
  proxy.$fn.checkForm(formRefs.value).then(() => {
    const details = tableInfo.data.filter((row) => row.productId)
    if (!details.length) {
      proxy.$message({
        message: '请添加有效的产品',
        type: 'warning',
        duration: 3500,
        showClose: true,
      })
      return
    }
    const api = createRfidBindList
    if (props.action !== 'add') {
      if (props.action === 'addBydeliverOrder') {
        details.forEach((element) => {
          element.supplierId = props.baseData.orgId
        })
      }
      if (props.action === 'addBydeliverOrder') {
        details.forEach((element) => {
          element.depotId = props.baseData.depotId
        })
      }
    }
    api(proxy.$fn.filterBlacklist(details)).then((resp) => {
      if (resp && resp.success) {
        showDialog.value = false
        emit('returnModify', false)
      }
    })
  })
}

//选择库存产品
function addProduct() {
  selectDepotStorageInfo.query.depotId.value = formInfo.data.depotId
  if (tableInfo.data.length) {
    selectDepotStorageInfo.query.id.value = tableInfo.data
      .map((item) => item.id)
      .toString()
  } else {
    selectDepotStorageInfo.query.id.value = ''
  }
  selectDepotStorageInfo.visible = true
}
async function selectDepotStorageCallBack(rows = []) {
  //库存产品返回
  tableInfo.data = tableInfo.data.concat(rows)
}
//删除产品
function removeProduct(row = undefined) {
  if (row && row.id) {
    tableInfo.data = tableInfo.data.filter((item) => item.id !== row.id)
  } else {
    proxy
      .$confirm('删除后将改变数据,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      .then(() => {
        tableInfo.data = tableInfo.data.filter((row) => {
          return !tableInfo.selections.includes(row)
        })
      })
  }
}
function getCustomize() {
  let param = {
    tableKey:
      'smartCabinetRfidBindAddPage-com.slip.spd.entity.vo.smartCabinet.SmartCabinetRfidBindVO',
  }
  tableInfo.isSysGroup = false
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      tableInfo.fieldList = proxy.$fn.setFieldList(
        tableInfo.fieldList,
        data.detail
      )
      for (let key in data.detail) {
        if (data.detail[key].sysGroupLevel > 0) {
          tableInfo.isSysGroup = true
        }
      }
      filterInfo.query.customizeUserVO = data
    }
  })
}
</script>

<style scoped lang="scss">
:deep(.page-table > .el-table) {
  overflow: hidden;
}
</style>
